<template>
  <div class="user-list-container">
    <div class="page-header">
      <span class="page-title">用户列表</span>
    </div>

    <div class="search-bar">
      <el-input
        v-model="queryInfo.keyword"
        placeholder="请输入用户名"
        clearable
        class="search-input"
        @keyup.enter="handleSearch"
        @clear="handleClear"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #append>
          <el-button :icon="Search" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
      <div class="action-buttons">
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        <el-button 
          type="danger" 
          :disabled="!selectedRows.length"
          @click="batchDeleteUser"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userName" label="姓名" />
      <el-table-column prop="sex" label="性别" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.row)" />
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <span class="total">共 {{ total }} 条</span>
      <el-select v-model="pageSize" class="page-size" @change="handleSizeChange">
        <el-option :value="5" label="5条/页" />
        <el-option :value="10" label="10条/页" />
        <el-option :value="20" label="20条/页" />
      </el-select>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加用户"
      width="500px"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="addForm.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="addForm.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="editForm.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userList, userAdd, userUpdate, userDelete, userBatchDelete } from '@/api/user'

const loading = ref(false)
const queryInfo = ref({
  keyword: '',
  pageNo: 1,
  pageSize: 5
})

const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const selectedRows = ref([])
const tableData = ref([])

// 添加用户对话框
const addDialogVisible = ref(false)
const addForm = ref({
  userName: '',
  sex: '男',
  email: '',
  address: ''
})

// 添加用户表单ref
const addFormRef = ref(null)
const submitLoading = ref(false)

// 添加用户表单校验规则
const addFormRules = {
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 重置添加表单
const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  addForm.value = {
    userName: '',
    sex: '男',
    email: '',
    address: ''
  }
}

// 提交添加用户
const submitAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    submitLoading.value = true
    
    const res = await userAdd(addForm.value)
    if (res.code === 200) {
      ElMessage.success('添加用户成功')
      addDialogVisible.value = false
      resetAddForm()
      getUserList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '添加用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('添加用户失败:', error)
      ElMessage.error('添加用户失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 打开添加对话框
const handleAdd = () => {
  addDialogVisible.value = true
  resetAddForm()
}

// 编辑相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  id: '',
  userName: '',
  sex: '男',
  email: '',
  address: ''
})

// 编辑表单校验规则
const editFormRules = {
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 重置编辑表单
const resetEditForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  editForm.value = {
    id: '',
    userName: '',
    sex: '男',
    email: '',
    address: ''
  }
}

// 打开编辑对话框
const handleEdit = (row) => {
  editForm.value = {
    id: row.id,
    userName: row.userName,
    sex: row.sex,
    email: row.email,
    address: row.address
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    submitLoading.value = true
    
    const res = await userUpdate(editForm.value)
    if (res.code === 200) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      resetEditForm()
      getUserList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '修改失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改用户失败:', error)
      ElMessage.error('修改失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    const res = await userDelete(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getUserList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除用户
const batchDeleteUser = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的用户吗？', '提示', {
      type: 'warning'
    })
    
    // 提取选中行的id并直接作为数组传递
    const ids = selectedRows.value.map(row => row.id)
    console.log('批量删除的ids:', ids) // 添加调试日志
    
    const res = await userBatchDelete(ids)
    
    if (res.code === 200) {
      ElMessage.success('批量删除成功')
      selectedRows.value = [] // 清空选中
      getUserList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 获取用户列表数据
const getUserList = async () => {
  try {
    loading.value = true
    const res = await userList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: queryInfo.value.keyword.trim() // 直接使用userName作为搜索参数
    })
    
    if (res.code === 200) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
      currentPage.value = res.data.current || currentPage.value
      
      if (tableData.value.length === 0 && queryInfo.value.keyword) {
        ElMessage.warning(`未找到包含 "${queryInfo.value.keyword}" 的用户`)
      }
    } else {
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}
// 处理页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getUserList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  getUserList()
}

const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  getUserList()
}

// 清空搜索
const handleClear = () => {
  queryInfo.value.keyword = ''
  currentPage.value = 1
  getUserList()
}

// 页面加载时获取数据
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-list-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total {
  margin-right: 10px;
  color: #606266;
}

.page-size {
  width: 100px;
  margin-right: 10px;
}

:deep(.el-button.is-circle) {
  margin-right: 10px;
}

:deep(.el-pagination) {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-input__prefix) {
  margin-left: 8px;
  color: #909399;
}

:deep(.el-input__wrapper) {
  padding-left: 0;
}

:deep(.el-input-group__append button) {
  padding: 0 20px;
}
</style> 